using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace CuthluralSwitcher.Library
{
    public class ImageManager
    {
        public static Image ResizeImage(Image FullsizeImage, int NewWidth, int MaxHeight, int MinHeight, bool OnlyResizeIfWider)
        {
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            int NewHeight = FullsizeImage.Height;
            if (FullsizeImage.Width < NewWidth)
            {
                float ratio = ((float)NewWidth / (float)FullsizeImage.Width);
                NewHeight = (int)Math.Floor((float)FullsizeImage.Height * ratio);
                if (NewHeight < MinHeight)
                {
                    NewHeight = MinHeight;
                    ratio = ((float)NewHeight / (float)FullsizeImage.Height);
                    NewWidth = (int)Math.Floor((float)FullsizeImage.Width * ratio);
                }
            }
            else if (FullsizeImage.Height < MinHeight)
            {
                NewHeight = MinHeight;
                float ratio = ((float)NewHeight / (float)FullsizeImage.Height);
                NewWidth = (int)Math.Floor((float)FullsizeImage.Width * ratio);
            }
            else if (FullsizeImage.Width > NewWidth)
            {
                float ratio = ((float)NewWidth / (float)FullsizeImage.Width);
                NewHeight = (int)Math.Floor((float)FullsizeImage.Height * ratio);
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();

            return NewImage;
        }
    }
}
